<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="站点名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入站点名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!--      <el-form-item label="状态" prop="status">-->
      <!--        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">-->
      <!--          <el-option-->
      <!--            v-for="dict in statusOptions"-->
      <!--            :key="dict.dictValue"-->
      <!--            :label="dict.dictLabel"-->
      <!--            :value="dict.dictValue"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <el-form-item label="客户端" prop="wxClientId" v-has-role="['admin']">
        <el-select v-model="queryParams.wxClientId" placeholder="请选择客户端" clearable size="small">
          <el-option
            v-for="item in clientList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hps:site:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hps:site:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hps:site:remove']"
        >删除
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hps:site:export']"
        >导出</el-button>
      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="siteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="站点名称" align="center" prop="name"/>
<!--      <el-table-column label="报名链接" align="center" prop="url"/>-->
      <!--      <el-table-column label="开赛时间" align="center" prop="kssj" >-->
      <!--      <template slot-scope="scope">-->
      <!--        <span>{{scope.row.kssj}} - {{scope.row.jssj}}</span>-->
      <!--      </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="开赛时间" prop="kssj" align="center"/>
      <el-table-column label="报名时间" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.bmsj}} - {{scope.row.jzsj}}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="状态" align="center" prop="status">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span :class="'common_status_'+scope.row.status">{{statusFormat(scope.row)}}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column label="客户端" align="center" prop="wxClientName" v-if="handleCheckRole('admin')"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hps:site:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hps:site:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-bicycle"
            @click="openTrail(scope.row.id)"
            v-hasPermi="['hps:trail:trailMap']"
          >骑行轨迹
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改竞赛站点对话框 -->
    <el-dialog v-if="open" class="abow_dialog" :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="first">

            <el-form-item label="站点名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入站点名称"/>
            </el-form-item>

<!--            <el-form-item label="报名链接" prop="url">-->
<!--              <el-input v-model="form.url" placeholder="请输入报名链接"/>-->
<!--            </el-form-item>-->
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="位置" prop="latitude">
                  <el-button size="medium" @click="mapDialog=true">点击选择坐标</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="经度" prop="longitude">
                  <el-input v-model="form.longitude" />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="维度" prop="latitude">
                  <el-input v-model="form.latitude" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入站点详细地址"/>
            </el-form-item>

            <el-form-item label="开赛时间" prop="date2">
              <el-date-picker
                v-model="form.date2"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm"
                :clearable="false"
                style="width: 100%"/>
            </el-form-item>
            <el-form-item label="报名时间" prop="date">
              <el-date-picker
                v-model="form.date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                style="width: 100%"/>
            </el-form-item>

            <!--            <el-form-item label="状态">-->
            <!--              <el-radio-group v-model="form.status">-->
            <!--                <el-radio-->
            <!--                  v-for="dict in statusOptions"-->
            <!--                  :key="dict.dictValue"-->
            <!--                  :label="dict.dictValue"-->
            <!--                >{{dict.dictLabel}}</el-radio>-->
            <!--              </el-radio-group>-->
            <!--            </el-form-item>-->

            <el-form-item label="封面图" prop="logo">
              <ImageUpload v-model="form.logo"/>
            </el-form-item>

            <el-form-item label="选择分组">
            </el-form-item>
            <el-table ref="multipleTable" v-loading="loading" :data="groupList"
                      @selection-change="handleSelectionChange2">
              <el-table-column type="selection" width="55" align="center" v-if="siteEnrollNum==0"/>
              <el-table-column label="组名" align="center" prop="name"/>
              <el-table-column label="人数" align="center" prop="num"/>
              <el-table-column label="最小年龄" align="center" prop="minAge"/>
              <el-table-column label="最大年龄" align="center" prop="maxAge"/>
              <el-table-column label="金额" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.amount" placeholder="请输入金额"
                            oninput="if(value){console.log(value);value=value.replace(/^\.+|[^\d.]/g,'');}"
                            v-if="siteEnrollNum==0"/>
                  <el-input v-model="scope.row.amount" placeholder="请输入金额" :disabled="true" v-if="siteEnrollNum>0"/>
                </template>
              </el-table-column>
            </el-table>


          </el-tab-pane>
          <el-tab-pane label="竞赛规则" name="second">
            <vue-ueditor-wrap v-model="form.rule" :config="myConfig1"></vue-ueditor-wrap>
          </el-tab-pane>
          <el-tab-pane label="报名须知" name="bmxz">
            <vue-ueditor-wrap v-model="form.bmxz" :config="myConfig2"></vue-ueditor-wrap>
          </el-tab-pane>
          <el-tab-pane label="站点地图" name="third">
            <vue-ueditor-wrap v-model="form.map" :config="myConfig3"></vue-ueditor-wrap>
          </el-tab-pane>
        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')" :loading="submitLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 地图定位弹框 -->
    <el-dialog title="获取地图坐标" :visible.sync="mapDialog" v-if="mapDialog" width="1000px" append-to-body>
      <GetCoordinate ref="map"></GetCoordinate>
      <span slot="footer">
    <el-button @click="mapDialog = false" size="mini">取 消</el-button>
    <el-button @click="getCoordinate" size="mini" type="primary">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  import {listSite, getSite, delSite, addSite, updateSite, exportSite, getSiteNum} from "@/api/hps/site";
  import {listEnroll} from "@/api/hps/enroll";
  import {listSiteGroup} from "@/api/hps/group";
  import {listClient} from "@/api/wx/client";
  import {checkPermi, checkRole} from "@/utils/permission.js";
  import VueUeditorWrap from 'vue-ueditor-wrap';
  import ImageUpload from '@/components/ImageUpload';
  import GetCoordinate from '@/views/components/map/locationMap';

  export default {
    name: "site",
    components: {
      VueUeditorWrap,
      ImageUpload,
      GetCoordinate
    },
    data() {
      let checkBmsj = function (rule, value, callback) {
        console.log(value)
        if (value) {
          callback();
        } else {
          callback(new Error('请选择时间'));
        }
      };

      let checkKssj = function (rule, value, callback) {
        console.log(value)
        if (value) {
          callback();
        } else {
          callback(new Error('请选择时间'));
        }
      };

      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 分组非单个禁用
        single2: true,
        // 分组非多个禁用
        multiple2: true,
        //存赛点分组内容
        groupInfoList: [],
        //提交form表单确认按钮加载效果
        submitLoading: false,
        //分组选中状态
        multipleSelection: [],
        //勾选分组金额校验
        rulesGroup: false,
        //赛事报名存在人数
        siteEnrollNum: 0,
        // 总条数
        total: 0,
        // 竞赛站点表格数据
        siteList: [],
        // 环鄱赛分组表格数据
        groupList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态字典
        statusOptions: [],
        //报名时间
        date: [],
        //开赛时间
        date2: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          dataType: '0'
        },
        // 查询分组参数
        queryParamsGroup: {
          pageNum: 1,
          pageSize: 30,
          name: undefined,
          num: undefined,
          minAge: undefined,
          maxAge: undefined,
          status: undefined,
          wxClientId: undefined,
          siteId: undefined
        },
        // 查询报名参数
        queryParamsEnroll: {
          siteId: undefined
        },
        // 表单参数
        form: {
          dataType: '0',
          latitude:'',
          longitude:'',
        },
        // 表单校验
        rules: {
          name: [
            {required: true, message: "不能为空", trigger: "blur"}
          ],
          status: [
            {required: true, message: '请选择状态', trigger: 'blur'}
          ],
          // url: [
          //   {required: true, message: '不能为空', trigger: 'blur'}
          // ],
          kssj: [
            {required: true, message: '请选择开赛时间', trigger: 'blur'}
          ],
          jssj: [
            {required: true, message: '请选择结束时间', trigger: 'blur'}
          ],
          date: [
            {required: true, validator: checkBmsj, trigger: 'blur'}
          ],

          date2: [
            {required: true, validator: checkKssj, trigger: 'blur'}
          ],
        },

        clientList: [],
        activeName: 'first',
        myConfig: {
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: 340,
          // 初始容器宽度
          initialFrameWidth: '100%',
          //启用自动保存
          enableAutoSave: true,
          // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！部署在国外的服务器，如果无法访问，请自备梯子）
          serverUrl: process.env.VUE_APP_BASE_API + '/api/ueditor/controller?userId=' + this.$store.getters.userInfo.userId,
          // serverUrl:'http://35.201.165.105:8000/controller.php',
          // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
          UEDITOR_HOME_URL: '/ueditor/',
          zIndex: 3001,
        },
        myConfig1: {
        },
        myConfig2: {
        },
        myConfig3: {
        },
        //地图
        mapDialog: false
      };
    },
    created() {
      this.getList();
      this.getDicts("system_common_status").then(response => {
        this.statusOptions = response.data;
      });
      if (checkRole(['admin'])) {
        listClient().then(response => {
          this.clientList = response.rows;
        });
      }
    },
    methods: {
      handleCheckRole(v) {
        return checkRole([v]);
      },
      /** 查询竞赛站点列表 */
      getList() {
        this.loading = true;
        listSite(this.queryParams).then(response => {
          this.siteList = response.rows;
          this.total = response.total;
          this.loading = false;
        });


      },

      // 状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.myConfig1 = {};
        this.myConfig2 = {};
        this.myConfig3 = {}
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          name: undefined,
          content: undefined,
          logo: undefined,
          url: undefined,
          rule: undefined,
          map: undefined,
          kssj: undefined,
          status: "1",
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          wxClientId: undefined,
          groupInfo: undefined,
          bmxz: undefined,
          bmsj: undefined,
          jzsj: undefined,
          jssj: undefined,
        };
        this.resetForm("form");
      },

      //打开骑行轨迹
      openTrail(id) {
        this.reset();
        console.log('id', id);
        this.queryParamsEnroll.siteId = id;
        listEnroll(this.queryParamsEnroll).then(response => {
          //获取第一条数据的经纬度，设置成地图初始显示位置
          var check = 0;
          var path = {
            lng: '',
            lat: ''
          }
          response.rows.forEach(item => {
            if (item.longitude != undefined && item.longitude != '' && check == 0) {
              path.lat = item.latitude;
              path.lng = item.longitude;
              check = 1;
            }
          })
          var location = '/zcth/order/yeanOrder';
          this.$router.push({'path': location, name: 'TrailMap', 'query': {siteId: id, lat: path.lat, lng: path.lng}})
        });


      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange2(selection) {
        this.single2 = selection.length != 1
        this.multiple2 = !selection.length;
        var groupList = [];
        selection.map(item => {
          var list = {
            groupId: item.id,
            amount: item.amount
          }
          groupList.push(list)
        })
        this.groupInfoList = groupList;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.myConfig1 = this.myConfig;
        this.myConfig2 = this.myConfig;
        this.myConfig3 = this.myConfig;
        //清空分组List
        this.groupList = [];
        this.queryParamsGroup.siteId = undefined;
        //设置报名人数为0
        this.siteEnrollNum = 0;
        //查询赛点分组
        listSiteGroup(this.queryParamsGroup).then(response => {
          this.groupList = response.rows;
          this.total = response.total;
          this.loading = false;
          console.log(this.groupList)
        });
        this.reset();
        //清空时间段缓存
        this.date = [];
        this.date2 = [];
        this.submitLoading = false;
        this.open = true;
        this.title = "添加竞赛站点";
        console.log(this.groupList)
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.myConfig1 = this.myConfig;
        this.myConfig2 = this.myConfig;
        this.myConfig3 = this.myConfig;
        //清空分组List
        this.groupList = [];
        this.queryParamsGroup.siteId = row.id || this.ids;
        //查询赛点分组
        listSiteGroup(this.queryParamsGroup).then(response => {
          this.groupList = response.rows;
          this.multipleSelection = response.rows;
          var ref = this.$refs;
          setTimeout(function () {
            response.rows.forEach(row => {
              if (row.amount != null && row.amount != '') {
                ref.multipleTable.toggleRowSelection(row);
              }
            });
          }, 100);
        });
        //获取赛点报名存在人数
        var siteId = row.id;
        this.siteEnrollNum = 0;
        getSiteNum(siteId).then(response => {
          this.siteEnrollNum = response.data.num;
        });

        this.reset();
        const id = row.id || this.ids
        getSite(id).then(response => {
          this.form = response.data;

          //回显报名时间
          this.date = [];
          if (response.data.bmsj != null && response.data.bmsj != undefined && response.data.bmsj != '') {
            this.date.push(response.data.bmsj);
            this.date.push(response.data.jzsj);
          }
          //回显开赛时间
          this.date2 = [];
          if (response.data.kssj != null && response.data.kssj != undefined && response.data.kssj != '') {
            this.date2.push(response.data.kssj);
            this.date2.push(response.data.jssj);
          }

          this.$set(this.form, 'date', this.date);
          this.$set(this.form, 'date2', this.date2);
          this.form.date = this.date;
          this.submitLoading = false;
          this.open = true;
          this.title = "修改竞赛站点";
        });
      },
      /** 提交按钮 */
      submitForm: function (form) {
        //勾选判断
        var rulesGroup = false;
        //没有任何勾选判断
        var rulesGroup2 = true;
        //设置选择分组内容List
        var groupInfoList = this.groupInfoList;
        //设置一个接收选择分组内容List
        var groupInfoList2 = [];
        if (this.siteEnrollNum > 0) {
          rulesGroup2 = false;
        }
        console.log(groupInfoList)
        //循环所有分组，判断是否与选中的分组ID相等，相等再判断金额是否为空，不为空把循环的分组金额设置到选中的分组金额中
        this.groupList.forEach(function (item) {
          groupInfoList.forEach(function (item2) {
            if (item.id == item2.groupId) {
              var list = {
                groupId: item.id,
                amount: item.amount
              }
              rulesGroup2 = false;
              console.log("进入分组校验")
              if (item.amount == null || item.amount == "" || parseFloat(item.amount) <= 0) {
                rulesGroup = true;
              } else {
                groupInfoList2.push(list)
              }
            }
          });

        });
        console.log(rulesGroup2)
        //判断选择的分组金额是否为空
        if (rulesGroup || rulesGroup2) {
          if (rulesGroup2) {
            this.$message.error('请勾选分组并输入相应的金额');
          } else {
            this.$message.error('勾选的分组金额不能为空或小于等于0');
          }
          rulesGroup = false;
        } else {
          this.$refs["form"].validate(valid => {
            if (valid) {
              if (this.form.id != undefined) {
                //获取报名时间段时间
                this.form.bmsj = this.form.date[0];
                this.form.jzsj = this.form.date[1];
                //获取开赛时间段时间
                this.form.kssj = this.form.date2[0];
                this.form.jssj = this.form.date2[1];

                this.form.groupInfo = JSON.stringify(groupInfoList2);
                //确认按钮显示加载中，无法点击
                this.submitLoading = true;
                updateSite(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  }
                });
              } else {
                //获取时间段时间
                this.form.bmsj = this.form.date[0];
                this.form.jzsj = this.form.date[1];
                //获取开赛时间段时间
                this.form.kssj = this.form.date2[0];
                this.form.jssj = this.form.date2[1];
                this.form.groupInfo = JSON.stringify(groupInfoList2);
                //确认按钮显示加载中，无法点击
                this.submitLoading = true;
                this.form.dataType = '0';
                addSite(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  }
                });
              }
            }
          });
        }

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除竞赛站点编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delSite(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有竞赛站点数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportSite(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      },
      handleClick(tab, event) {
        console.log(tab, event);
      },

      /**地图弹框确认获取定位*/
      getCoordinate() {
        if (this.$refs.map.pointInfo.location) {
          this.form.latitude = this.$refs.map.pointInfo.location.lat;
          this.form.longitude = this.$refs.map.pointInfo.location.lng;
          console.log(this.form)
          this.mapDialog = false
        } else {
        }
      },


    },

  };

</script>
